<template>
<div ref="wrapRef"></div>
    <BasicForm @register="registerForm"/>
</template>
<script lang="ts">
	import { ref, computed, unref, reactive, defineComponent, nextTick, onMounted } from "vue";
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {attendanceRecordFormSchema} from '../WorkOrder.data';
    import {defHttp} from '/@/utils/http/axios';
    import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils'
	import { useScript } from '/@/hooks/web/useScript';

    export default defineComponent({
        name:"AttendanceRecordForm",
        components: {BasicForm},
        emits:['register'],
        props:{
            disabled: {
                type: Boolean,
                default: false
            }
        },
        setup(props,{emit}) {
			const BAI_DU_MAP_URL = 'https://api.map.baidu.com/getscript?v=3.0&ak=cgcrS9Zur45rMLx3RcQCfTGPO1nBnE51&services=&t=20210201100830&s=1';
			const wrapRef = ref<HTMLDivElement | null>(null);
			const { toPromise } = useScript({ src: BAI_DU_MAP_URL });
            const [registerForm, {setProps, resetFields, setFieldsValue,getFieldsValue,validate}] = useForm({
                //labelWidth: 150,
                schemas: attendanceRecordFormSchema,
                showActionButtonGroup: false,
                baseColProps: {span: 24}
            });
            /**
            *初始化加载数据
            */
            function initFormData(url,id){
                if(id){
                     defHttp.get({url,params:{id}},{isTransformResponse:false}).then(res=>{
                       res.success && setFieldsValue({...res.result[0]});
                    })
                }
				
				initMap();
				//setFieldsValue({fullAddress:888888});
                setProps({disabled: props.disabled})
            }
			async function initMap() {
				console.log('99999999999999999999999999');
			  await toPromise();
			  await nextTick();
			  console.log('77777');
			  const wrapEl = unref(wrapRef);
			  
			  if (!wrapEl) return;
			  const BMap = (window as any).BMap;
			  const map = new BMap.Map(wrapEl);
			  // const point = new BMap.Point(116.404, 39.915);
			  // map.centerAndZoom(point, 15);
			  // map.enableScrollWheelZoom(true);
			  const geolocation = new BMap.Geolocation();

			  geolocation.enableSDKLocation(); // 启用SDK定位
			  geolocation.getCurrentPosition(function(r) {
				if (this.getStatus() == BMAP_STATUS_SUCCESS) {
				  const point = new BMap.Point(r.point.lng, r.point.lat);
				  // 获取位置成功，可以通过r.point获取坐标
				  const mk = new BMap.Marker(r.point);
				  map.addOverlay(mk); // 在地图中添加点
				  map.panTo(r.point); // 将地图中心设置为定位点
				  // 创建逆地址解析实例
				  var geoc = new BMap.Geocoder();

				  // 执行逆地址解析
				  geoc.getLocation(point, function(rs){
					var addComp = rs.addressComponents;
					// 获取地址结果
					var address = rs.address; // 获取地址
					// 输出地址信息
					console.log(rs);
					console.log(address);
					// alert(rs.content.address+rs.content.poi_desc);
					//row.fullAddress = rs.content.address+rs.content.poi_desc;
					setFieldsValue({fullAddress:rs.content.address+rs.content.poi_desc});
				  });
				} else {
				  // 获取位置失败
				  alert('定位失败！');
				}
			  }, {enableHighAccuracy: true});
			}
           /**
            *获取表单数据
            */
            function getFormData(){
               let formData = getFieldsValue();
               Object.keys(formData).map(k=>{
                    if(formData[k] instanceof Array){
                        formData[k] = formData[k].join(',')
                    }
               });
               return [formData];
            }
            /**
            *表单校验
            */
            function validateForm(index){
                return new Promise((resolve, reject) => {
                    // 验证子表表单
                    validate().then(()=>{
                        return resolve()
                    }).catch(()=> {
                        return reject({ error: VALIDATE_FAILED ,index})
                    })
                })
            }
            return {
                registerForm,
                resetFields,
                initFormData,
                getFormData,
                validateForm,
				initMap,
				toPromise,
				BAI_DU_MAP_URL,
				wrapRef
            }
        }
    })
</script>
